#!/usr/bin/perl

# ------------------------------------------------------------------------------
# --- Add new PDBs into the workflow manager DB
# ------------------------------------------------------------------------------

use strict;
use warnings;

use Time::Piece;
use DBI;

# Get current time for "date_added" field in pdb table
my $t = localtime;
my $rightnow = $t->ymd . ' ' . $t->hms;

# Get list of PDB IDs
my $pdb_list = shift;

defined $pdb_list
	or die "ERROR: Must pass PDB list file name.\n";

open (PDB, "<$pdb_list")
	or die "ERROR: Could not open PDB list $pdb_list.\n";

# Connect to database
my $dbh = DBI->connect(
	"dbi:SQLite:dbname=workflow_tracker.db",
	"",
	"",
	{ RaiseError => 1 },
) or die $DBI::errstr;

foreach my $pdb (<PDB>) {

	chomp $pdb;

	# Execute SQL command to insert (non-redundant) PDB codes into the DB

	my $insert_sql = "INSERT INTO pdb (pdb_id) SELECT '$pdb' ";
	$insert_sql   .= "WHERE NOT EXISTS (SELECT 1 FROM pdb WHERE pdb_id = '$pdb');";

	print STDERR "$insert_sql\n";

	my $sth = $dbh->prepare($insert_sql);
	$sth->execute();
	$sth->finish();
	
}

# Execute SQL command to change all NULL dates to today's date
my $date_sql = "UPDATE pdb SET date_added = '$rightnow' WHERE date_added IS NULL;";

print STDERR $date_sql . "\n";

my $sth = $dbh->prepare($date_sql);
$sth->execute();
$sth->finish();

$dbh->disconnect();

exit;
